package controller;

import entity.Action;
import entity.User;
import manager.UserManager;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class LoginController extends SimpleFormController {

    List<Action> listActions = new LinkedList<Action>();
    UserManager userManager;

    public LoginController() {
        setCommandClass(User.class);
        setCommandName("customerForm");
    }

    @Override
    protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception {
        HashMap<String, Object> map = new HashMap<String, Object>();
        User user = (User) command;
        User findUser = userManager.searchUser(user.getName());
        if (findUser == null || !findUser.getPass().equals(user.getPass())) {
            return new ModelAndView("loginResult", "map", map);
        }
        putAction(user.getName());
        String now = (new Date()).toString();
        map.put("name", user.getName());
        map.put("now", now);
        map.put("action", listActions);
        return new ModelAndView("home", "map", map);
    }

    private void putAction(String role) {
        listActions = new LinkedList<Action>();
        Action searchAction = new Action("search.htm", "Search Books");
        Action reservationAction = new Action("reservation.htm", "Reservation Books");
        Action stateAction = new Action("state.htm", "Books State");
        Action borrowAction = new Action("lending.htm", "Lending Book");
        Action returnAction = new Action("return.htm", "Return Book");
        listActions.add(searchAction);
        listActions.add(reservationAction);
        listActions.add(stateAction);
        if (role.equals("admin")) {
            listActions.add(borrowAction);
            listActions.add(returnAction);
        }
    }

    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }
}